package com.shikSMS.init;

import com.shikSMS.manage.service.SmsLogService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManager;
import java.io.File;
import java.lang.management.ManagementFactory;
import java.net.URL;

/**
 * @author gengshikun
 * @date 2017/12/01
 */
@Component
public class InitRunner implements CommandLineRunner {

    @Autowired
    private EntityManager em;

    @Autowired
    private SmsLogService smsLogService;

    @Override
    public void run(String... strings) throws Exception {

        getPID();

    }


    /**
     * 获取当前程序的PID
     *
     * @throws Exception
     */
    private static void getPID() throws Exception {
        // get name representing the running Java virtual machine.
        String name = ManagementFactory.getRuntimeMXBean().getName();
        // get pid
        final String pid = name.split("@")[0];
        System.out.println("Pid is:" + pid);

        // 获取上下文路径
        URL url = InitRunner.class.getResource("");
        System.out.println("cotextPath:" + url);
        if (url != null) {
            String cotextPath = url.getPath();
            if (cotextPath.contains(".jar!")) {// 说明是jar包
                cotextPath = cotextPath.substring(0, cotextPath.indexOf("!"));
                cotextPath = cotextPath.substring(0, cotextPath.lastIndexOf("/"));
            } else {// 不然从线程里得
                url = Thread.currentThread().getContextClassLoader()
                        .getResource("");
                if (url != null) {
                    cotextPath = url.getPath();
                } else {
                    throw new Exception("无法生成PID文件");
                }
            }
            if (cotextPath.contains("file:")) {// 针对windows的情况
                cotextPath = cotextPath.replace("file:", "");
            }

            // String cotextPath = "/var/run/";
            System.out.println("cotextPath:" + cotextPath);

            // 写PID文件
            FileUtils.writeStringToFile(new File(cotextPath + "/sms.pid"), pid,"UTF-8");
        }
    }

}
